package org.ubc.cs410.disposal2020.client;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

/*
 * implementation of joining a game
 */

public class JoinGame implements EntryPoint, ClickHandler {

	private static final String LOADING = "Loading...";
	private Label createGameLabel;
	private ListBox listBox;
	private Button joinButton;
	private GameServiceAsync gameService;

	@Override
	public void onModuleLoad() {
		init();

		createGameLabel = new Label("Select a Game to join");
		joinButton = new Button("Join");

		joinButton.addClickHandler(this);

		listBox = new ListBox();
		listBox.addItem(LOADING);

		loadGameToModel();

		VerticalPanel mainPanel = new VerticalPanel();
		HorizontalPanel controlPanel = new HorizontalPanel();
		controlPanel.add(createGameLabel);
		controlPanel.add(listBox);
		controlPanel.add(joinButton);

		mainPanel.add(controlPanel);

		RootPanel.get("joinPanel").add(mainPanel);
	}

	private void init() {
		gameService = (GameServiceAsync) GWT.create(GameService.class);
		ServiceDefTarget endpoint = (ServiceDefTarget) gameService;
		endpoint.setServiceEntryPoint("/services/game");
	}

	private void loadGameToModel() {

		gameService.listAvailableGames(new AsyncCallback<Map<String,String>>() {

			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(Map<String,String> result) {
				listBox.clear();
				for (Entry<String, String> game : result.entrySet()) {
					listBox.addItem(game.getValue(), game.getKey());
				}
			}
		});
	}

	@Override
	public void onClick(ClickEvent event) {

		final String selectedGame = listBox.getValue(listBox
				.getSelectedIndex());
		if (!selectedGame.equals(LOADING)) {

			gameService.joinGame(selectedGame, new AsyncCallback<String>() {

				@Override
				public void onFailure(Throwable caught) {
				}

				@Override
				public void onSuccess(String result) {
					if (result != null) {
						redirect("/game/" + selectedGame);
					} else {
						Window.alert("Fail to Join Game: " + selectedGame);
					}
				}
			});
		}
	}

	native void redirect(String url)
	/*-{
		$wnd.location.replace(url);
	}-*/;

}